var dbConfig = require("./index")
const jwt = require('jsonwebtoken');
const { SECRET_KEY } = require("../config/index")
const dayjs = require('dayjs');
const getToken = (data) => jwt.sign({ data }, SECRET_KEY, { expiresIn: "8h" })
const { Parameters, fieldDesc } = require('../utils/utils')
//登录生成token
const login = (req, res) => {
  console.log(req.body);
  const { account, password } = req.body
  if (!account || !password) return res.send({ code: 200, data: null, msg: '请输入账号密码' })
  const sql = `select * from users where account=? and password=?`
  dbConfig.sqlConnect(sql, [account, password], (data, err) => {
    if (!data.length) return res.send({
      code: 401,
      data: { token: null },
      msg: '账号或密码错误,请确认后登录'
    })
    res.send({
      code: 200,
      data: {
        token: getToken(data[0]),
        effectiveTime: dayjs().add(8, 'h').format('YYYY-MM-DD HH:mm:ss')
      },
      msg: null
    })
  }, res)
}
//注册账号
const register = (req, res) => {
  /**
   * 账号重复验证成功调用增加数据接口
  */
  const adopt = () => {
    fieldDesc({
      "phone": "手机号",
      "password": "密码",
      "userName": "用户名",
      "account": "账号"
    }, req.body, res, () => {
      const { keys, values, num } = new Parameters(req.body).add({
        status: 1,//状态默认为正常 1正常 0停用
        rule: 0,//权限默认为普通用户 1为vip admin 管理员
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      })
      const sql = `insert into node_test.users(${keys}) values(${num})`
      dbConfig.sqlConnect(sql, [...values], () => {
        res.sends(null, '账号创建成功')
      }, res)
    })
  }

  /**
   * 账号重复性验证
  */
  dbConfig.sqlConnect('select * from users where account=?', [req.body?.account], (data) => {
    if (data?.length === 0) adopt()
    else res.sendError(null, '账号重复!')
  }, res)

}


module.exports = { login, register }
